﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using NetBee.Business;
using NetBee.Config;
using System.Linq;
namespace NetBee
{
    /// <summary>
    /// 采集数据窗口
    /// xue8000@gmail.com
    /// </summary>
    public partial class NetBeeForm : Form
    {
        public NetBeeForm()
        {
            InitializeComponent();
        }

        private void Menu_Functions_TaskRunner_Click(object sender, EventArgs e)
        {
            #region//
            System.Threading.ParameterizedThreadStart pts = new System.Threading.ParameterizedThreadStart(StartGatherForMySql);
            System.Threading.Thread t = new System.Threading.Thread(pts);
            t.IsBackground = true;
            t.Name = "采集数据-mysql";
            t.Start(this.MenuBar_Functions_TaskRunner);
            #endregion
        }
        private void StartGatherForMySql(dynamic obj)
        {
            OperateMenuItem(this.MenuBar_Functions_TaskRunner, false);//禁用菜单项
            #region//任务计时
            var watch = new System.Diagnostics.Stopwatch();
            watch.Restart();
            Gatherer gatherer = new Gatherer(this, 10);
            #region//执行任务
            #region//step 1.反序列化 任务编号列表
            var settings = new NetBeeSettings();
            var json = settings.ExecuteTasks;
            var Tasks = new List<int>();
            var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(Tasks.GetType());
            try
            {
                using (var ms = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(json)))
                {
                    ms.Position = 0;
                    Tasks = serializer.ReadObject(ms) as List<int>;
                }
            }
            catch
            {
                System.Diagnostics.Debug.Assert(false, "配置ExecuteTasks错误 ...请配置为 [1,2,3] 的样式");
            }
            #endregion
            #region//step 2.循环执行任务
            foreach (var taskId in Tasks)
            {
                try
                {
                    gatherer.Gather(taskId);
                }
                catch (Exception e)
                {
                    System.Diagnostics.Debug.Assert(false, string.Format("执行任务时发生异常:{0}" + Environment.NewLine + "堆栈信息:{1}" + Environment.NewLine + "内部异常:{2}" + Environment.NewLine + "内部堆栈信息:{3}", e.Message,
                        e.StackTrace, e.InnerException.Message, e.InnerException.StackTrace));
                }
            }
            #endregion
            #endregion
            watch.Stop();
            this.Print(this.txt_Screen, string.Format("抓取完成耗时{0}天{1}小时{2}分{3}秒{4}毫秒" + Environment.NewLine, watch.Elapsed.Days, watch.Elapsed.Hours, watch.Elapsed.Minutes, watch.Elapsed.Seconds, watch.Elapsed.Milliseconds));
            #endregion
            OperateMenuItem(this.MenuBar_Functions_TaskRunner, true);//启用菜单项
        }

        #region//操作本窗体上的控件
        #region//显示文本
        private delegate void ProxyPrint(RichTextBox controller, string msg);
        internal void Print(RichTextBox controller, string msg)
        {
            if (controller.InvokeRequired)
            {
                ProxyPrint print = new ProxyPrint(Print);
                this.Invoke(print, controller, msg);
            }
            else
            {
                controller.AppendText(msg);
            }
        }
        #endregion

        #region//操作菜单项
        private delegate void ProxyMenuBar(ToolStripMenuItem menu, bool isEnable);
        private void OperateMenuItem(ToolStripMenuItem menu, bool isEnable)
        {
            if (this.InvokeRequired)
            {
                var proxy = new ProxyMenuBar(OperateMenuItem);
                this.Invoke(proxy, menu, isEnable);
            }
            else
            {
                menu.Enabled = isEnable;
                if (isEnable)
                {
                    menu.Text = menu.Text.Replace("√", "");
                }
                else
                {
                    menu.Text += "√";
                }
            }
        }
        #endregion

        private void MenuBar_Functions_Export_Click(object sender, EventArgs e)
        {
            var settings = new NetBeeSettings();
            if (string.IsNullOrEmpty(settings.ExportPath))
            {
                settings.ExportPath = Environment.CurrentDirectory + "/Exports/";
            }
            #region//
            if (string.IsNullOrEmpty(settings.ExportDataByTasks))
            {
                System.Diagnostics.Debug.Assert(false, "请配置 ExportDataByTasks项,请按[1,2,3]配置...");
                return;
            }
            List<int> ids = new List<int>();
            try
            {
                var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(ids.GetType());
                var ms = new System.IO.MemoryStream(new System.Text.UTF8Encoding(false).GetBytes(settings.ExportDataByTasks));
                ids = serializer.ReadObject(ms) as List<int>;
                using (var entities = new NetBee.Entity.MySql.NetBeeEntities())
                {
                    if (!System.IO.Directory.Exists(settings.ExportPath)) {
                        System.IO.Directory.CreateDirectory(settings.ExportPath);
                    }
                    foreach (var id in ids)
                    {
                        var data = entities.NetBee_GatherData.AsNoTracking().Where(i => i.TaskId == id).ToList();
                        foreach (var xml in data)
                        {
                            System.IO.File.WriteAllText(settings.ExportPath + DateTime.Now.Ticks.ToString()+".xml", xml.Data);
                        }
                    }
                }
            }
            catch {
                System.Diagnostics.Debug.Assert(false, "导出数据时发生异常~");
            }
            #endregion
            

        }
        #endregion
    }
}
